package com.goldgov.oauth2filter;

import com.goldgov.config.FilterProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 过滤器
 * @author guor
 */
public class PreRequestFilter implements Filter {
    /**
     * 加载filter配置内容
     * @param filterProperties
     */
    public PreRequestFilter(FilterProperties filterProperties){
        this.filterProperties=filterProperties;
    }

    @Autowired
    FilterProperties filterProperties;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response1 = (HttpServletResponse)response;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        String contextPath = ((HttpServletRequest) request).getContextPath();
        //替换context路径
        requestURI=requestURI.replace(contextPath,"");
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        //免过滤地址，即不需要oauth2（统一认证）处理的请求
        List<String> ignored = filterProperties.getIgnored();
        if (!CollectionUtils.isEmpty(ignored)){
            for (int i = 0; i <ignored.size() ; i++) {
                if (antPathMatcher.match(ignored.get(i),requestURI)){
                    chain.doFilter(request,response);
                    return;
                }
            }
        }
        //已登录继续后续过滤器
        if(authentication!=null&& authentication.isAuthenticated()&&!(authentication instanceof AnonymousAuthenticationToken) ){
            chain.doFilter(request,response);
        }else{
            //未登录跳转统一认证界面，结束过滤链
            String oauth2Server = filterProperties.getOauth2Server();
            Assert.notNull(oauth2Server,"oauth2服务端地址未配置，请检查配置文件中的。kcloud.oauth2-filter.oauth2-server");
            if(!oauth2Server.endsWith("/")){
                oauth2Server+="/";
            }
            response1.sendRedirect(oauth2Server +"oauth/authorize?response_type=code&client_id="+filterProperties.getClientId()+"&redirect_uri="+filterProperties.getRedirectUri()+"&state="+ URLEncoder.encode(requestURI,"UTF-8"));
            return;
        }
    }
}
